package com.service;

import cn.hutool.core.io.FileUtil;
import com.aes.AES;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dao.CardDAO;
import com.dao.ErrorCardDao;
import com.dao.StaffDAO;
import com.modal.BatchUpdateStaffZhiYeModel;
import com.pojo.Dictionary;
import com.pojo.*;
import com.util.*;
import com.vo.StaffVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: T-bao
 * @Date: 2021-3-27 17:45
 * @Description:
 */
@Service
public class StaffService extends ServiceImpl<StaffDAO, Staff> {

    @Autowired
    private StaffDAO staffDAO;

    @Autowired
    private CardDAO cardDAO;

    @Autowired
    private ErrorCardDao errorCardDao ;

    @Autowired
    private AlertService alertService;

    @Autowired
    private SshCopyFileService sshCopyFileService;

    @Value("${upload.dir}")
    private String upload;

    @Value("${upload.tmp.dir}")
    private String tmp;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private QiyeService qiyeService;

    @Autowired
    private WuyeService wuyeService;

    @Autowired
    private StaffHistoryService staffHistoryService;

    @Value("${minio.basicsUrl}")
    private String BasicsUrl;

    @Value("${minio.privateBucketName}")
    private String PrivateBucketName;

    @Value("${minio.accessKey}")
    private String AccessKey;

    @Value("${minio.secretKey}")
    private String SecretKey;

    @Value("${minio.endpoint}")
    private String Endpoint;

    public static List<Staff> staffList = new ArrayList<>();

    /***
     * 获取员工id和sfz信息
     * 这里只查特行的职业
     * @return
     */
    public List<Staff> getAllStaffWithSfz(){
        List  staffListTemp = new ArrayList();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("id","sfz","zhiye");
        List<Staff> list = staffDAO.selectList(queryWrapper);
        for (Staff staff:list){
            String sfz = staff.getSfz();
            String newSfz = staff.getSfz();
            if (sfz!=null && sfz.startsWith("$#")){
                newSfz = AES.decrypt(sfz.substring(3));
            }
            Staff newStaff = new Staff();
            newStaff.setId(staff.getId());
            newStaff.setSfz(newSfz);
            newStaff.setZhiye(staff.getZhiye());
            staffListTemp.add(newStaff);
        }
        staffList.clear();
        staffList = staffListTemp;
        return staffList;
    }

    /**
     * 根据身份证查员工
     * @param sfz  要查的身份证，支持查糊查询
     * @param  zhiyeNames  要职业名字集合,null則查所有職業
     * @return 编号集合
     */
    public List<String> searchSfz(String sfz,List<String> zhiyeNames){
        List  ids = new ArrayList();
        if (StringUtil.isNull(sfz))
            return  ids;
        for (Staff s: staffList){
            String sfzStr = s.getSfz();

            if (sfzStr!=null && sfzStr.contains(sfz)){
                String zhiye = s.getZhiye();
                if (zhiyeNames==null || zhiyeNames.size()==0 || zhiyeNames.contains(zhiye))
                {
                    String id = s.getId();
                    ids.add(id);
                }
            }
        }
        return ids;
    }

    /**
     * 根据身份证查员工
     * @param sfz  要查的身份证，支持查糊查询
     * @return 编号集合
     */
    public List<String> searchSfzNoZy(String sfz){
        List  ids = new ArrayList();
        if (StringUtil.isNull(sfz))
            return  ids;
        for (Staff s: staffList){
            String sfzStr = s.getSfz();

            if (sfzStr!=null && sfzStr.contains(sfz)){
                String id = s.getId();
                ids.add(id);
            }
        }
        return ids;
    }



    /**
     * 查找未审核员工
     * @param name 员工姓名
     * @return
     */
    public int shenhecount(String name){
        return staffDAO.shenhecount(name);
    }

    /**
     * 分页查找未审核员工
     * @param name  员工姓名
     * @param page
     * @param limit
     * @return
     */
    public List<StaffVO> shenheStaff(String name, int page, int limit){
        return staffDAO.shenheStaff(name,page,limit);
    }

    /**
     * 根据员工ID查找员工
     * @param id
     * @return
     */
    public Staff selectID(String id){
        return staffDAO.selectById(id);
    }

    /**
     * 根据员工姓名或员工编号查找员工
     * @param staffID   员工编号或员工姓名
     * @return
     */
    public Staff selectNameID(String staffID){
        return staffDAO.selectOne(new QueryWrapper<Staff>().eq("name",staffID).or().eq("bh",staffID));
    }

    /**
     * 根据员工编号和员工ID查询员工数量
     * @param id    员工ID
     * @param bh    员工编号
     * @return
     */
    public int countBhID(String id,String bh){
        return staffDAO.selectList(new QueryWrapper<Staff>().eq("bh",bh).eq("id",id)).size();
    }

    /**
     * 根据员工编号查员工数量
     * @param bh    员工编号
     * @return
     */
    public int countBh(String bh){
        return staffDAO.selectList(new QueryWrapper<Staff>().eq("bh",bh)).size();
    }

    /**
     * 根据证件号查询员工数量
     * @param sfz   证件号
     * @return
     */
    public int sfzCount(String sfz){
        return staffDAO.selectList(new QueryWrapper<Staff>().eq("sfz",sfz)).size();
    }

    /**
     * 根据员工姓名查询员工数量
     * @param name  员工姓名
     * @return
     */
    public int countName(String name){
        List<Staff> staff = staffDAO.selectList(new QueryWrapper<Staff>().eq("name" , name)) ;
        return staff.size();
    }

    /**
     * 根据员工姓名和ID查询员工数量
     * @param name  员工姓名
     * @param id    员工ID
     * @return
     */
    public int countNameID(String name,String id){
        List<Staff> staff = staffDAO.selectList(new QueryWrapper<Staff>().eq("name" , name).eq("id",id)) ;
        return staff.size();
    }

    /**
     * 分页查询员工
     * @param name  员工姓名
     * @param page
     * @param limit
     * @param wuye  所属物业
     * @param qiye  所属企业
     * @param zhiye 职业
     * @param guoji 国籍
     * @return
     */
    public IPage<StaffVO> selectStaff(String name, int page, int limit , String wuye , String qiye, String zhiye, String guoji, String queryStr){
//        if (page == 1) {
//            page = 0;
//        } else {
//            page = (page * limit) - limit;
//        }
        if(StringUtil.isNotNull(wuye)) {
            if(StringUtil.isNull(qiye)) {
                qiye = null ;
            }
            if(StringUtil.isNull(name)) {
                name = null ;
            }
            if(StringUtil.isNull(guoji) || guoji.equals("选择国籍")) {
                guoji = null ;
            }
        }

        List<String> zyNameList = new ArrayList<>();
        if(StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            if (StringUtil.isNotNull(queryStr)) {
                List<Dictionary> zyList = new ArrayList<>();
                if ("gs".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyGs();
                }else if ("jt".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyJt();
                }
                if (ValidateHelper.isNotEmptyCollection(zyList)) {
                    for (Dictionary dictionary : zyList) {
                        if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                            zyNameList.add(dictionary.getName());
                        }
                    }
                }
            }
            zhiye = null ;
        }

        Integer status = 0;
        List<String> ids = searchSfz(name,zyNameList);
        IPage<StaffVO> iPage = staffDAO.selectByQyWy(new Page(page,limit) , name , wuye , qiye,status,zhiye, guoji, queryStr, zyNameList, ids) ;
        return iPage ;
    }

    /**
     * 根据员工id查询用户是否是特行办
     * @param zy 员工职业
     * @return
     */
    public boolean isThb(String zy){

        Dictionary dic = dictionaryService.getDicByName("Zy", zy);

        return dic != null && "thb".equals(dic.getValue());
    }

    /**
     * 查询员工数量
     * @param name  员工姓名
     * @param wuye  所属物业
     * @param qiye  所属企业
     * @param zhiye 职业
     * @param guoji 国籍
     * @return
     */
    public int selectCountStaff(String name , String wuye , String qiye, String zhiye, String guoji, String queryStr) {
        Integer status = 0;
        List<String> zyNameList = new ArrayList<>();
        if(StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            if (StringUtil.isNotNull(queryStr)) {
                List<Dictionary> zyList = new ArrayList<>();
                if ("gs".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyGs();
                }else if ("jt".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyJt();
                }
                if (ValidateHelper.isNotEmptyCollection(zyList)) {
                    for (Dictionary dictionary : zyList) {
                        if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                            zyNameList.add(dictionary.getName());
                        }
                    }
                }
            }
            zhiye = null ;
        }
        List<String> ids = searchSfz(name,zyNameList);
        return  staffDAO.selectCountByQyWy(name,wuye,qiye,status,zhiye,guoji, queryStr, zyNameList, ids);
    }

    public IPage<Staff> selectStaffGP(String name, int page, int limit , String wuye , String qiye, String zkFlag, String zhiye, String dataFlag, String queryStr){
        if(StringUtil.isNull(wuye)) {
            wuye = null ;
        }
        if(StringUtil.isNull(qiye)) {
            qiye = null ;
        }
        if(StringUtil.isNull(name)) {
            name = null ;
        }
        if(StringUtil.isNull(zkFlag)) {
            zkFlag = null ;
        }
        List<String> zyNameList = new ArrayList<>();
        if(StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            if (StringUtil.isNotNull(queryStr)) {
                List<Dictionary> zyList = new ArrayList<>();
                if ("gs".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyGs();
                }else if ("jt".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyJt();
                }
                if (ValidateHelper.isNotEmptyCollection(zyList)) {
                    for (Dictionary dictionary : zyList) {
                        if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                            zyNameList.add(dictionary.getName());
                        }
                    }
                }
            }
            zhiye = null ;
        }
        if (ValidateHelper.isEmptyString(dataFlag)) {
            dataFlag = null;
        }
        Page p = new Page(page , limit) ;
        Integer status = 1;

        IPage<Staff> iPage = staffDAO.selectByGp(p , name , wuye , qiye, status, zkFlag, zhiye, dataFlag, queryStr, zyNameList) ;

        return iPage ;
    }

    public IPage<Staff> selectStaffGPByProblemData(String name, int page, int limit , String wuye , String qiye, String zkFlag, String zhiye){
        if(StringUtil.isNull(wuye)) {
            wuye = null ;
        }
        if(StringUtil.isNull(qiye)) {
            qiye = null ;
        }
        if(StringUtil.isNull(name)) {
            name = null ;
        }
        if(StringUtil.isNull(zkFlag)) {
            zkFlag = null ;
        }
        if(StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            zhiye = null;
        }

        Page p = new Page(page , limit) ;
        QueryWrapper<Staff> query = new QueryWrapper() ;
        final String name1 = name ;
        if(StringUtil.isNotNull(name)) {
            query.and(q -> {
                q.like("name" , "%"+name1+"%").or().like("bh","%"+name1+"%").or().like("phone","%"+name1+"%").or().like("sfz","%"+name1+"%") ;
            }) ;
        }
        if(StringUtil.isNotNull(qiye)) {
            query.eq("qyId" , qiye) ;
        }

        if(StringUtil.isNotNull(zhiye) && !zhiye.equals("选择职业")) {
            query.eq("zhiye" , zhiye) ;
        }

        if (StringUtil.isNotNull(zkFlag)) {
            if ("1".equals(zkFlag)) {
                query.eq("zk_flag" , zkFlag) ;
            }else if ("0".equals(zkFlag)){
                query.and( q -> {
                    q.eq("zk_flag","0").or().isNull("zk_flag");
                });
            }else {
                query.eq("zk_flag" , "") ;
            }
        }

        //审核状态为已审核
        query.eq("shstatus",1);
        //状态为在职
        query.eq("status",1);
        Integer status = 1;
        IPage<Staff> iPage = staffDAO.selectByGpByProblemData(p , name , wuye , qiye, status, zkFlag, zhiye) ;
        return iPage ;
    }

    public IPage<StaffVO> selectStaffByCard(String name, int page, int limit , String wuye , String qiye, String cardStatus, String queryStr){
        if(StringUtil.isNull(wuye)) {
            wuye = null;
        }
        if(StringUtil.isNull(qiye)) {
            qiye = null ;
        }
        if(StringUtil.isNull(name)) {
            name = null ;
        }
        if(StringUtil.isNull(cardStatus)) {
            cardStatus = null;
        }
        List<String> zyNameList = new ArrayList<>();
        if (ValidateHelper.isNotEmptyString(queryStr)) {
            List<Dictionary> zyList = new ArrayList<>();
            if ("gs".equals(queryStr)) {
                zyList = dictionaryService.getDicByZyGs();
            }else if ("jt".equals(queryStr)) {
                zyList = dictionaryService.getDicByZyJt();
            }
            if (ValidateHelper.isNotEmptyCollection(zyList)) {
                for (Dictionary dictionary : zyList) {
                    if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                        zyNameList.add(dictionary.getName());
                    }
                }
            }
        }
        IPage<StaffVO> staffList = staffDAO.selectStaffByCard(new Page(page, limit), name , wuye , qiye, 1, cardStatus, queryStr, zyNameList) ;
        return staffList ;
    }

    public IPage<Staff> selectStaffByShbk(String name, int page, int limit , String wuye , String qiye){

        Page p = new Page(page , limit) ;
//        QueryWrapper<Staff> query = new QueryWrapper() ;
//        final String name1 = name ;
//        if(StringUtil.isNotNull(name)) {
//            query.and(q -> {
//                q.like("name" , "%"+name1+"%").or().like("bh","%"+name1+"%").or().like("card_no","%"+name1+"%");
//            }) ;
//        }
//
//        query.and(q -> {
//            q.isNotNull("card_no").or().eq("card_no" , "");
//        });
//
//        //审核状态为已审核
//        query.eq("shstatus",1);
//        //状态为在职
//        query.eq("status",1);
//
//        if(StringUtil.isNotNull(qiye)) {
//            query.eq("qyId" , qiye) ;
//        }

        if(StringUtil.isNotNull(wuye)) {
            if(StringUtil.isNull(qiye)) {
                qiye = null ;
            }
            if(StringUtil.isNull(name)) {
                name = null ;
            }
            Integer status = 1;
            IPage<Staff> iPage = staffDAO.selectByShbk(p , name , wuye , qiye,status) ;
            return iPage ;
        }else{
            if(StringUtil.isNull(qiye)) {
                qiye = null ;
            }
            if(StringUtil.isNull(wuye)) {
                wuye = null ;
            }
            if(StringUtil.isNull(name)) {
                name = null ;
            }
            IPage<Staff> iPage = staffDAO.selectStaffByCard1(p , name , wuye , qiye,1) ;
            return iPage ;
        }
//        else{
//            IPage<Staff> iPage = staffDAO.selectStaffByCard1(p , name , wuye , qiye,1) ;
//            return iPage ;
//        }
//        IPage<Staff> iPage = staffDAO.selectPage(new Page(page , limit) , query) ;
//        return iPage ;
    }

    public IPage<Staff> selectStaffKk(int page, int limit , String name, String wuye , String qiye, String zhiye, String queryStr){
        Page p = new Page(page , limit) ;
        QueryWrapper<Staff> query = new QueryWrapper() ;
        final String name1 = name ;
        if(StringUtil.isNotNull(name)) {
            query.and(q -> {
                q.like("name" , "%"+name1+"%").or().like("bh","%"+name1+"%").or().like("phone","%"+name1+"%").or().like("sfz","%"+name1+"%") ;
            }) ;
        }
        if(StringUtil.isNotNull(qiye)) {
            query.eq("qyId" , qiye) ;
        }
        if(StringUtil.isNotNull(zhiye) && !zhiye.equals("选择职业")) {
            query.eq("zhiye" , zhiye) ;
        }
        //审核状态为已审核
        query.eq("shstatus",1);
        //状态为在职
        query.eq("status",1);

        query.and(q -> {
            q.isNull("card_no").or().eq("card_no" , "") ;
        });

        List<String> zyNameList = new ArrayList<>();
        if(StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            if (StringUtil.isNotNull(queryStr)) {
                List<Dictionary> zyList = new ArrayList<>();
                if ("gs".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyGs();
                }else if ("jt".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyJt();
                }
                if (ValidateHelper.isNotEmptyCollection(zyList)) {
                    for (Dictionary dictionary : zyList) {
                        if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                            zyNameList.add(dictionary.getName());
                        }
                    }
                }
                query.in("zhiye", zyNameList);
            }
            zhiye = null ;
        }

        if(StringUtil.isNotNull(wuye)) {
            if(StringUtil.isNull(qiye)) {
                qiye = null ;
            }
            if(StringUtil.isNull(name)) {
                name = null ;
            }
            Integer status = 1;
            IPage<Staff> iPage = staffDAO.selectByKk(p , name , wuye , qiye,status,null, zhiye, queryStr, zyNameList) ;
            return iPage ;
        }
        IPage<Staff> iPage = staffDAO.selectPage(p,query) ;
        return iPage ;
    }

    /**
     * 根据员工姓名查询员工数量
     * @param name  员工姓名
     * @return
     */
    public int count(String name){
        return staffDAO.count(name);
    }

    /**
     * 分页查询快到期员工
     * @param name  员工姓名
     * @param page
     * @param limit
     * @param time
     * @param cstime    到期时间
     * @return
     */
    public List<StaffVO> kuaidaoqiStaff(String name, int page, int limit, Date time, Date cstime){
        return staffDAO.kuaidaoqiStaff(name,page,limit,time,cstime);
    }

    /**
     * 查询快到期员工数量
     * @param name
     * @param time
     * @param cstime 到期时间
     * @return
     */
    public int kdqcount(String name,Date time,Date cstime){
        return staffDAO.kdqcount(name,time,cstime);
    }

    public List<StaffVO> yidaoqiStaff(String name, int page, int limit, Date time){
        return staffDAO.yidaoqiStaff(name,page,limit,time);
    }

    /**
     * 查询已到期员工数量
     * @param name
     * @param time
     * @return
     */
    public int ydqcount(String name,Date time){
        return staffDAO.ydqcount(name,time);
    }

    /**
     * 根据员工ID修改员工状态
     * @param id    员工ID
     * @return
     */
    public Staff upshStatus(String id){
        Staff theme = staffDAO.selectById(id);
        if (theme==null)
            return theme;

        Integer oldStatus = theme.getShstatus();
        if (oldStatus==null)
            oldStatus = 0 ;

        theme.setShstatus(1-oldStatus);

        staffDAO.updateById(theme);
        return theme;
    }

    /**
     * 修改员工
     * @param staff
     * @return
     */
    public int upStatus(Staff staff){
        return staffDAO.updateById(staff);
    }

    /**
     * 查询物业包含员工
     * @param wy    物业
     * @param page
     * @param limit
     * @return
     */
    public IPage<Staff> staffListByWy(String wy , Integer page , Integer limit) {
        return staffDAO.staffListByWy(new Page(page , limit) , wy) ;
    }

    /**
     * 根据卡号获取用户信息
     * @param cardNo 卡号
     * @return
     */
    public Map<String,Object> getStaffInfoByCz(String cardNo, String queryStr){
        Map<String,Object> resultMap = new HashMap<>();
        QueryWrapper<Card> query = new QueryWrapper();

        List<String> zyNameList = new ArrayList<>();
        if (ValidateHelper.isNotEmptyString(queryStr)) {
            List<Dictionary> zyList = new ArrayList<>();
            if ("gs".equals(queryStr)) {
                zyList = dictionaryService.getDicByZyGs();
            }else if ("jt".equals(queryStr)) {
                zyList = dictionaryService.getDicByZyJt();
            }
            if (ValidateHelper.isNotEmptyCollection(zyList)) {
                for (Dictionary dictionary : zyList) {
                    if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                        zyNameList.add(dictionary.getName());
                    }
                }
            }
        }


        if (StringUtil.isNotNull(cardNo)){
            query.eq("xuliehao",cardNo);
            query.last("limit 1");
            Card card = cardDAO.selectOne(query);
            if (null != card) {
                resultMap.put("cardStatus",getCardStatus(card.getStatus()));
                Staff staff = new Staff();
                if (ValidateHelper.isNotEmptyString(queryStr)) {
                    staff = staffDAO.selectOne(new QueryWrapper<Staff>().eq("id",card.getStaffId()).in("zhiye", zyNameList).last("limit 1"));
                }else {
                    staff = staffDAO.selectById(card.getStaffId());
                }
                if (null != staff){
                    resultMap.put("staff",staff);
                    if (null == staff.getCardBalance()) {
                        resultMap.put("balance",0);
                    }else {
                        resultMap.put("balance",staff.getCardBalance());
                    }
                }
            }else {
                List<Staff> staffs = staffDAO.selectList(new QueryWrapper<Staff>().eq("card_no",cardNo));
                if (staffs.size() <= 0) {
                    return resultMap;
                }else {
                    resultMap.put("staff",staffs.get(0));
                }
            }
        }
        return resultMap;
    }

    public Staff getStaffInfo(String userName,String password) {
        QueryWrapper<Staff> query = new QueryWrapper();
        query.eq("name",userName).eq("password","password");
        List<Staff> staffList = staffDAO.selectList(query);
        if (null != staffList) {
            return staffList.get(0);
        }
        return null;
    }

    /**
     * 员工登录
     * @param phone     员工编号
     * @param password  密码
     * @return
     */
    public Staff getStaffInfoByLogin(String phone,String password) {
        QueryWrapper<Staff> query = new QueryWrapper();
        query.eq("bh",phone).eq("password",password);
        List<Staff> staffList = staffDAO.selectList(query);
        if (staffList.size() != 0) {
            return staffList.get(0);
        }
        return null;
    }


    /**
     * 根据员工编号查找员工
     * @param bh
     * @return
     */
    public List<Staff> getStaffInfoByBh(String bh) {
        QueryWrapper<Staff> query = new QueryWrapper();
        query.eq("bh",bh);
        query.orderByDesc("createtime");
        List<Staff> staffList = staffDAO.selectList(query);
        if (staffList.size() > 0) {
            return staffList;
        }
        return new ArrayList<>();
    }

    public List<Staff> getStaffInfoByExport(String name,String wuye,String qiye, String zhiye, String guoji, String queryStr) {
        if(StringUtil.isNotNull(wuye)) {
            if(StringUtil.isNull(qiye)) {
                qiye = null ;
            }
            if(StringUtil.isNull(name)) {
                name = null ;
            }
        }

        List<String> zyNameList = new ArrayList<>();
        if(StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            if (StringUtil.isNotNull(queryStr)) {
                List<Dictionary> zyList = new ArrayList<>();
                if ("gs".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyGs();
                }else if ("jt".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyJt();
                }
                if (ValidateHelper.isNotEmptyCollection(zyList)) {
                    for (Dictionary dictionary : zyList) {
                        if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                            zyNameList.add(dictionary.getName());
                        }
                    }
                }
            }
            zhiye = null ;
        }
        List<String> ids = searchSfz(name,zyNameList);
        List<Staff> staffList =staffDAO.selectByExport(name,wuye,qiye, zhiye, guoji, queryStr, zyNameList, ids);
        return staffList ;
    }


    public List<StaffVO> exportExcelByGp(String name, String wuye, String qiye, String zkFlag, String zhiye, String dataFlag, String queryStr) {
        Integer status = 1;
        List<String> zyNameList = new ArrayList<>();
        if(StringUtil.isNotNull(wuye)) {
            if(StringUtil.isNull(qiye)) {
                qiye = null ;
            }
            if(StringUtil.isNull(name)) {
                name = null ;
            }
            if(StringUtil.isNull(zkFlag)) {
                zkFlag = null ;
            }
        }
        if(StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            if (StringUtil.isNotNull(queryStr)) {
                List<Dictionary> zyList = new ArrayList<>();
                if ("gs".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyGs();
                }else if ("jt".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyJt();
                }
                if (ValidateHelper.isNotEmptyCollection(zyList)) {
                    for (Dictionary dictionary : zyList) {
                        if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                            zyNameList.add(dictionary.getName());
                        }
                    }
                }
            }
            zhiye = null ;
        }
        List<StaffVO> staffList = staffDAO.exportExcelByGp(name , wuye , qiye,status,zkFlag, zhiye, dataFlag, queryStr, zyNameList) ;
        if (staffList.size() > 0) {
            // 如果是问题数据，则给员工备注加上问题数据描述
            if ("1".equals(dataFlag)) {
                for (StaffVO staff : staffList) {
                    boolean flag = false;
                    StringBuffer sb = new StringBuffer();
                    if (ValidateHelper.isEmptyString(staff.getName())) {
                        sb.append("姓名为空");
                        flag = true;
                    }
                    if (staff.getName().contains("\n")) {
                        sb.append("，姓名包含换行符");
                        flag = true;
                    }

                    if (ValidateHelper.isEmptyString(staff.getBh())) {
                        sb.append("，编号为空");
                        flag = true;
                    }
                    if (staff.getBh().contains("\n")) {
                        sb.append("，编号包含换行符");
                        flag = true;
                    }
                    if (!staff.getBh().matches("^[A-Z]{2}\\d.*?")) {
                        sb.append("，编号前两位必须是大写英文字母");
                        flag = true;
                    }

                    if (ValidateHelper.isEmptyString(staff.getPicture()) || staff.getPicture().equals("null")) {
                        sb.append("，没有上传照片");
                        flag = true;
                    }else {
                        File file = new File(upload + staff.getPicture());
                        if (!file.exists()) {
                            sb.append("，照片不存在");
                            flag = true;
                        }
                    }

                    if (ValidateHelper.isEmptyString(staff.getCsTime())) {
                        sb.append("，出生日期为空");
                        flag = true;
                    }else {
                        if (staff.getCsTime().startsWith("00")) {
                            sb.append("，出生日期为0000/00/00");
                            flag = true;
                        }
                    }
                    if (ValidateHelper.isEmptyString(staff.getZhiye())) {
                        sb.append("，职业为空");
                        flag = true;
                    }
                    List<Alert> alertList = alertService.getAlertByStaff(staff.getId());
                    if (ValidateHelper.isNotEmptyCollection(alertList)) {
                        sb.append("，" + alertList.get(0).getContent());
                        flag = true;
                    }
                    if (flag) {
                        String msg = sb.toString();
                        if (msg.startsWith("，")) {
                            msg = msg.substring(1,msg.length());
                        }
                        staff.setMessage(msg);
                    }
                }
            }

        }
        return staffList ;
    }

    /**
     * 导出问题数据员工
     * @param queryStr
     * @return
     */
    public List<StaffVO> exportExcelByProblemData(String queryStr) {
        List<StaffVO> resultList = new ArrayList<>();

        List<String> zyNameList = new ArrayList<>();
        if (ValidateHelper.isNotEmptyString(queryStr)) {
            List<Dictionary> zyList = new ArrayList<>();
            if ("gs".equals(queryStr)) {
                zyList = dictionaryService.getDicByZyGs();
            }else if ("jt".equals(queryStr)) {
                zyList = dictionaryService.getDicByZyJt();
            }
            if (ValidateHelper.isNotEmptyCollection(zyList)) {
                for (Dictionary dictionary : zyList) {
                    if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                        zyNameList.add(dictionary.getName());
                    }
                }
            }
        }

        List<StaffVO> staffList = staffDAO.exportExcelByProblemData(queryStr, zyNameList);

        if (staffList.size() > 0) {
            for (StaffVO staff : staffList) {
                boolean flag = false;
                StringBuffer sb = new StringBuffer();
                if (ValidateHelper.isEmptyString(staff.getName())) {
                    sb.append("姓名为空");
                    flag = true;
                }
                if (staff.getName().contains("\n")) {
                    sb.append("，姓名包含换行符");
                    flag = true;
                }

                if (ValidateHelper.isEmptyString(staff.getBh())) {
                    sb.append("，编号为空");
                    flag = true;
                }
                if (staff.getBh().contains("\n")) {
                    sb.append("，编号包含换行符");
                    flag = true;
                }
                if (!staff.getBh().matches("^[A-Z]{2}\\d.*?")) {
                    sb.append("，编号前两位必须是大写英文字母");
                    flag = true;
                }

                if (ValidateHelper.isEmptyString(staff.getPicture()) || staff.getPicture().equals("null")) {
                    sb.append("，没有上传照片");
                    flag = true;
                }else {
                    File file = new File(upload + staff.getPicture());
                    if (!file.exists()) {
                        sb.append("，照片不存在");
                        flag = true;
                    }
                }

                if (ValidateHelper.isEmptyString(staff.getCsTime())) {
                    sb.append("，出生日期为空");
                    flag = true;
                }else {
                    if (staff.getCsTime().startsWith("00")) {
                        sb.append("，出生日期为0000/00/00");
                        flag = true;
                    }
                }
                if (ValidateHelper.isEmptyString(staff.getZhiye())) {
                    sb.append("，职业为空");
                    flag = true;
                }
                if (ValidateHelper.isEmptyString(staff.getWyName())) {
                    sb.append("，物业为空");
                    flag = true;
                }
                if (ValidateHelper.isEmptyString(staff.getQyName())) {
                    sb.append("，企业为空");
                    flag = true;
                }
                if (flag) {
                    String msg = sb.toString();
                    if (msg.startsWith("，")) {
                        msg = msg.substring(1,msg.length());
                    }
                    staff.setMessage(msg);
                    resultList.add(staff);
                }
            }
        }
        return resultList ;
    }

    public List<Staff> errorPictureCopy () {
        List<Staff> resultList = new ArrayList<>();
        List<Staff> staffList = staffDAO.selectList(null);
        if (staffList.size() > 0) {
            int i = 0;
            for (Staff staff : staffList) {
                File file = new File(upload + staff.getPicture());

                if (ValidateHelper.isNotEmptyString(staff.getPicture()) && !staff.getPicture().equals("null") && !file.exists()) {
                    String picture = staff.getPicture().replaceAll(".JPG", ".jpg");
                    FileUtil.copy(tmp + picture, upload + staff.getPicture(), false) ;
                    i ++;
                    //resultList.add(staff);
                    /*String picture = staff.getPicture().replaceAll(".JPG" , ".jpg");
                    File tmpFile = new File(tmp + picture);
                    if (tmpFile.exists()) {
                        resultList.add(staff);
                    }*/
                }
            }
            System.out.println(i);
        }
        return resultList;
    }

    public List<Staff> getStaffInfoByQy(String qyId) {
        QueryWrapper<Staff> query = new QueryWrapper() ;
        if (StringUtil.isNotNull(qyId)) {
            query.eq("qyID",qyId);
        }
        List<Staff> staffList = staffDAO.selectList(query);
        if (staffList.size() > 0) {
            return staffList ;
        }
        return null;
    }

    /**
     * 根据员工编号查询员工
     * @param bh
     * @return
     */
    public Staff getStaffByBh(String bh) {
        QueryWrapper<Staff> query = new QueryWrapper();
        query.eq("bh",bh);
        query.orderByDesc("createtime");
        List<Staff> staffList = staffDAO.selectList(query);
        if (staffList.size() > 0) {
            return staffList.get(0);
        }
        return null;
    }

    public int getStaffByCard(String cardNo,String id) {
        List<Card> cardList = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao" , cardNo)) ;
        List<Staff> staffList = staffDAO.selectList(new QueryWrapper<Staff>().eq("card_no" , cardNo)) ;
        // 白卡
        if (ValidateHelper.isEmptyCollection(cardList) && ValidateHelper.isEmptyCollection(staffList)) {
            return 0;
        }
        if(ValidateHelper.isNotEmptyCollection(cardList)) {
            Staff staff = staffDAO.selectById(cardList.get(0).getStaffId()) ;
            if (staff == null) {
                return 1;
            }
            // 正常
            return 2 ;
        }else{
            return 1;
        }
//        QueryWrapper<Staff> query = new QueryWrapper();
//        if (StringUtil.isNotNull(id)) {
//            query.eq("id",id);
//        }
//        if (StringUtil.isNotNull(cardNo)) {
//            query.eq("card_no",cardNo);
//        }
//        List<Staff> staffList = staffDAO.selectList(query);
//        if (staffList.size() > 0) {
//            return staffList.get(0);
//        }
//        return null;
    }

    public Staff getStaffByCardNo(String cardNo) {
        List<Staff> staffList = staffDAO.selectList(new QueryWrapper<Staff>().eq("card_no" , cardNo)) ;
        if (staffList.size() > 0) {
            return staffList.get(0);
        }
        return null;
    }

    /**
     * 查询企业包含员工
     * @param qyId 企业ID
     * @return
     */
    public List<Staff> getStaffByQyId(String qyId) {
        List<Staff> staffList = staffDAO.selectList(new QueryWrapper<Staff>().eq("qyID" , qyId)) ;
        if (staffList.size() > 0) {
            return staffList;
        }
        return new ArrayList<>();
    }

    private String getCardStatus(Integer status) {
        if (status == 1) {
            return "启用";
        }else if (status == 2){
            return "停用";
        }else if (status == 3){
            return "挂失";
        }else {
            return "报废";
        }
    }

    /**
     * 校验用户编号是否正确
     * @param id
     * @return
     */
    public String checkBh(String id){
        Staff staff = staffDAO.selectById(id) ;
        if (!staff.getBh().matches("^[A-Z]{2}\\d[\\S\\s]*?")){
            return "编号有问题，无法制卡" ;
        }
        if (staff.getCstime().startsWith("00")) {
            return "员工出生日期为0000/00/00，无法制卡" ;
        }
        if (ValidateHelper.isEmptyString(staff.getPicture())) {
            return "员工头像为空，无法制卡" ;
        }
        if (ValidateHelper.isEmptyString(staff.getName())) {
            return "员工姓名为空，无法制卡" ;
        }
        List<Alert> alertList = alertService.getAlertByStaff(staff.getId());
        if (ValidateHelper.isNotEmptyCollection(alertList)) {
            return alertList.get(0).getContent();
        }
        return "" ;
    }

    /**
     * 校验用户编号是否正确
     * @param id
     * @return
     */
    public void checkBatch(String id, List<String> errorList){
        Staff staff = staffDAO.selectById(id) ;
        String error = "";
        if (ValidateHelper.isEmptyString(staff.getName())) {
            error = "<br><span style='color:red;'>姓名：</span>"  + staff.getName() +  "&nbsp&nbsp&nbsp&nbsp编号：" +  staff.getBh() +  "&nbsp&nbsp&nbsp&nbsp错误信息：<span style='color:red;'>员工姓名为空，无法完成制卡</span>";
            errorList.add(error) ;
        }
        if (!staff.getBh().matches("^[A-Z]{2}\\d[\\S\\s]*?")){
            error = "<br>姓名：" + staff.getName() + "&nbsp&nbsp&nbsp&nbsp编号：" + "<span style='color:red;'>" +  staff.getBh() + "</span>" + "&nbsp&nbsp&nbsp&nbsp错误信息：<span style='color:red;'>编号有问题，无法完成制卡</span>";
            errorList.add(error) ;
        }
        if (staff.getCstime().startsWith("00")) {
            error = "<br>姓名：" + staff.getName() + "&nbsp&nbsp&nbsp&nbsp编号：" +  staff.getBh() +  "&nbsp&nbsp&nbsp&nbsp出生日期：" + "<span style='color:red;'>" + staff.getCstime() + "</span>" + "&nbsp&nbsp&nbsp&nbsp错误信息：<span style='color:red;'>员工出生日期为0000/00/00，无法完成制卡</span>";
            errorList.add(error) ;
        }
        if (ValidateHelper.isEmptyString(staff.getPicture())) {
            error = "<br>姓名：" + staff.getName() + "&nbsp&nbsp&nbsp&nbsp编号：" +  staff.getBh() +  "&nbsp&nbsp&nbsp&nbsp错误信息：<span style='color:red;'>用户没有上传头像，无法完成制卡</span>";
            errorList.add(error) ;
        }
    }


    public void checkLoad(String id, List<String> errorList){
        Staff staff = staffDAO.selectById(id) ;
        if (!staff.getBh().matches("^[A-Z]{2}\\d[\\S\\s]*?") || staff.getCstime().startsWith("00")
                || ValidateHelper.isEmptyString(staff.getPicture()) || ValidateHelper.isEmptyString(staff.getName())){
            errorList.add(staff.getId()) ;
        }
    }

    /**
     * 解除卡绑定关系
     * @param id
     * @return
     */
    public String resetCard(String id){
        Staff staff = staffDAO.selectById(id) ;
        if(staff == null) {
            return "用户不存在" ;
        }
        if(StringUtil.isNull(staff.getCardNo())) {
            return "用户未绑定卡" ;
        }
//        List<Card> cards = cardDAO.selectList(new QueryWrapper<Card>().eq("xuliehao" , staff.getCardNo())) ;
//        if(cards.size() == 0) {
//            return "卡信息不存在" ;
//        }
//        String cardNo = staff.getCardNo() ;
//        String pin = staff.getPin() ;
        staffDAO.clearCard(id) ;
//        Card card = cards.get(0) ;
//        ErrorCard errorCard = new ErrorCard() ;
//        errorCard.setCardNo(cardNo);
//        errorCard.setMiyao(card.getMiyao());
//        errorCard.setPin(pin);
//        errorCard.setCtime(new Date());
//        errorCardDao.insert(errorCard) ;
//        cardDAO.deleteById(card) ;
        return null ;
    }

    /**
     * 卡与用户绑定
     * @param uid
     * @param cid
     * @return
     */
    public String bangdin(String uid , String cid){
        List<ErrorCard> errorCards = errorCardDao.selectList(new QueryWrapper<ErrorCard>().eq("card_no" , cid)) ;
        if(errorCards.size() == 0) {
            return "未找到卡信息" ;
        }
        Staff staff = staffDAO.selectById(uid) ;
        if(staff == null) {
            return "用户不存在" ;
        }
        if(StringUtil.isNotNull(staff.getCardNo())) {
            return "用户已经绑定卡" ;
        }
        ErrorCard errorCard = errorCards.get(0) ;
        Card card = new Card() ;
        card.setPin1(errorCard.getPin());
        card.setMiyao(errorCard.getMiyao());
        card.setStaffId(uid);
        card.setXuliehao(errorCard.getCardNo());
        card.setLuRuCreateTime(new Date());
        card.setStatus(1);
        cardDAO.insert(card) ;
        staff.setPin(errorCard.getPin());
        staff.setCardNo(errorCard.getCardNo());
        staffDAO.updateById(staff) ;
        errorCardDao.deleteById(errorCard) ;
        return null ;
    }

    /**
     * 卡与用户绑定
     * @param cid
     * @return
     */
    public String bangdin1(String cid){
        List<ErrorCard> errorCards = errorCardDao.selectList(new QueryWrapper<ErrorCard>().eq("card_no" , cid)) ;
        if(errorCards.size() == 0) {
            return "未找到卡信息" ;
        }


        ErrorCard errorCard = errorCards.get(0) ;
        Card card = new Card() ;
        card.setPin1(errorCard.getPin());
        card.setMiyao(errorCard.getMiyao());
        card.setXuliehao(errorCard.getCardNo());
        card.setLuRuCreateTime(new Date());
        card.setStatus(1);
        cardDAO.insert(card) ;
        errorCardDao.deleteById(errorCard) ;
        return null ;
    }

    public List<Map<String, Long>> getGuojiCount() {
        Map<String, Long> result = new HashMap<>();
        List<Map<String, Long>> mapList = staffDAO.getGuojiCount();
        /*if (ValidateHelper.isNotEmptyCollection(mapList)) {
            for (Map<String, Long> map: mapList) {
                Long count = null;
                String guoji = "";
                for (Map.Entry<String, Long> maps : map.entrySet()) {
                    if ("guoji".equals(maps.getKey())) {
                        guoji = String.valueOf(maps.getValue());
                    }
                    if ("countPeople".equals(maps.getKey())) {
                        count = maps.getValue();
                    }
                    result.put(guoji, count);
                }
            }
        }*/

        return mapList;
    }

    public IPage<StaffVO> getStaffTrail(Integer page, Integer limit, String name , String wuye , String qiye, String days) {
        Page p = new Page(page, limit);
        if (ValidateHelper.isEmptyString(name)) {
            name = null;
        }
        if (ValidateHelper.isEmptyString(wuye)) {
            wuye = null;
        }
        if (ValidateHelper.isEmptyString(qiye)) {
            qiye = null;
        }
        if (ValidateHelper.isEmptyString(days)) {
            days = null;
        }
        IPage iPage = staffDAO.getStaffTrail(p, name, wuye, qiye, days);
        return iPage;
    }


    public List<StaffVO> getStaffTrailByExport(String name , String wuye , String qiye, String days) {
        if (ValidateHelper.isEmptyString(name)) {
            name = null;
        }
        if (ValidateHelper.isEmptyString(wuye)) {
            wuye = null;
        }
        if (ValidateHelper.isEmptyString(qiye)) {
            qiye = null;
        }
        if (ValidateHelper.isEmptyString(days)) {
            days = null;
        }
        List<StaffVO> staffVOList = staffDAO.getStaffTrailByExport(name, wuye, qiye, days);
        return staffVOList;
    }

    public IPage<StaffVO> selectStaffQrCode(String name, int page, int limit , String wuye , String qiye, String zhiye, String qrCode){
        Page p = new Page(page, limit);
        if(StringUtil.isNull(wuye)) {
            wuye = null ;
        }
        if(StringUtil.isNull(qiye)) {
            qiye = null ;
        }
        if(StringUtil.isNull(name)) {
            name = null ;
        }
        if(StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            zhiye = null ;
        }
        if(StringUtil.isNull(qrCode)) {
            qrCode = null ;
        }
        Integer status = 0;
        IPage<StaffVO> iPage = staffDAO.selectByQrCode(p, name , wuye , qiye,status,zhiye, qrCode) ;
        return iPage ;
    }

    /**
     * 根据职业查询员工
     * @param zhiye 职业
     * @return
     */
    public List<Staff> getStaffByZhiye(String zhiye) {
        List<Staff> staffList = staffDAO.selectList(new QueryWrapper<Staff>().eq("zhiye" , zhiye)) ;
        if (staffList.size() > 0) {
            return staffList;
        }
        return new ArrayList<>();
    }


    /**
     * 分页查询黑白名单列表
     * @param name
     * @param page
     * @param limit
     * @param wuye
     * @param qiye
     * @param zhiye
     * @param whiteList
     * @param qrCode
     * @return
     */
    public IPage<StaffVO> selectStaffWhiteList(String name, int page, int limit , String wuye , String qiye, String zhiye, String whiteList, String qrCode, String queryStr){
        Page p = new Page(page, limit);
        if(StringUtil.isNull(wuye)) {
            wuye = null ;
        }
        if(StringUtil.isNull(qiye)) {
            qiye = null ;
        }
        if(StringUtil.isNull(name)) {
            name = null ;
        }
        if(StringUtil.isNull(whiteList)) {
            whiteList = null ;
        }
        if(StringUtil.isNull(qrCode)) {
            qrCode = null ;
        }

        List<String> zyNameList = new ArrayList<>();
        if(StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            if (StringUtil.isNotNull(queryStr)) {
                List<Dictionary> zyList = new ArrayList<>();
                if ("gs".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyGs();
                }else if ("jt".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyJt();
                }
                if (ValidateHelper.isNotEmptyCollection(zyList)) {
                    for (Dictionary dictionary : zyList) {
                        if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                            zyNameList.add(dictionary.getName());
                        }
                    }
                }
            }
            zhiye = null ;
        }
        Integer status = 0;
        IPage<StaffVO> iPage = staffDAO.selectStaffWhiteList(p, name , wuye , qiye,status,zhiye, whiteList, qrCode, queryStr, zyNameList) ;
        return iPage ;
    }

    /**
     * 导出黑白名单
     * @param name
     * @param wuye
     * @param qiye
     * @param zhiye
     * @param whiteList
     * @param qrCode
     * @return
     */
    public List<StaffVO> exportStaffWhiteList(String name, String wuye , String qiye, String zhiye, String whiteList, String qrCode, String queryStr){
        if(StringUtil.isNull(wuye)) {
            wuye = null ;
        }
        if(StringUtil.isNull(qiye)) {
            qiye = null ;
        }
        if(StringUtil.isNull(name)) {
            name = null ;
        }
        if(StringUtil.isNull(whiteList)) {
            whiteList = null ;
        }
        if(StringUtil.isNull(qrCode)) {
            qrCode = null ;
        }
        List<String> zyNameList = new ArrayList<>();
        if(StringUtil.isNull(zhiye) || zhiye.equals("选择职业")) {
            if (StringUtil.isNotNull(queryStr)) {
                List<Dictionary> zyList = new ArrayList<>();
                if ("gs".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyGs();
                }else if ("jt".equals(queryStr)) {
                    zyList = dictionaryService.getDicByZyJt();
                }
                if (ValidateHelper.isNotEmptyCollection(zyList)) {
                    for (Dictionary dictionary : zyList) {
                        if (ValidateHelper.isNotEmptyString(dictionary.getName())) {
                            zyNameList.add(dictionary.getName());
                        }
                    }
                }
            }
            zhiye = null ;
        }
        Integer status = 0;
        List<StaffVO> iPage = staffDAO.exportStaffWhiteList(name , wuye , qiye,status,zhiye, whiteList, qrCode, queryStr, zyNameList) ;
        return iPage ;
    }

    /**
     * 获取员工健康码及健康码生成原因
     * @param staffId
     * @return
     */
    public Map<String, String> getQrCode (String staffId) {
        Map result = new HashMap();
        Staff staff = staffDAO.selectById(staffId);
        if (staff.getWhiteList() == 1) {
            result.put("red", "员工属于黑名单");
            return result;
        }else {
//            Hesuan hesuan = hesuanService.getLastResultHs(staffId);
//            if (ValidateHelper.isNotEmptyString(staff.getQrcode())) {
//                if (null != staff.getWhite_time() && null != staff.getQrCodeExpDay()) {
//                    if (null == hesuan || null == hesuan.getCreateTime() || (null != hesuan.getCreateTime() && hesuan.getCreateTime().before(staff.getWhite_time()))) {
//                        if (null != staff.getWhite_time() && null != staff.getQrCodeExpDay()) {
//                            Date curDate = new Date();
//                            long days = curDate.getTime() - staff.getWhite_time().getTime();
//                            if (days <= (staff.getQrCodeExpDay().longValue() * (1000*3600*24L))) {
//                                result.put(staff.getQrcode(), "白名单健康码有效期内");
//                                return result;
//                            }
//                        }
//                    }
//                }
//            }
        }

        Integer orangeDay = 3;
        if ("工商从业人员".equals(staff.getZhiye())) {
            List<Dictionary> dictionaryList = dictionaryService.getDicByType("GsOrangeDay");
            if (ValidateHelper.isNotEmptyCollection(dictionaryList)) {
                orangeDay = Integer.valueOf(dictionaryList.get(0).getValue());
            }
        }else if ("特种行业从业人员".equals(staff.getZhiye())) {
            List<Dictionary> dictionaryList = dictionaryService.getDicByType("TzOrangeDay");
            if (ValidateHelper.isNotEmptyCollection(dictionaryList)) {
                orangeDay = Integer.valueOf(dictionaryList.get(0).getValue());
            }
        }else {
            List<Dictionary> dictionaryList = dictionaryService.getDicByType("OrangeDay");
            if (ValidateHelper.isNotEmptyCollection(dictionaryList)) {
                orangeDay = Integer.valueOf(dictionaryList.get(0).getCode());
            }
        }

        if (null != staff.getJcFlag()) {
            if (staff.getJcFlag() == 1) {
//                List<Hesuan> hesuanList = hesuanService.selectHs(staff.getId());
//                if (hesuanList.size() > 0) {
//                    if (hesuanList.get(0).getJcResult() == 1) {
//                        Date curDate = new Date();
//                        long days = curDate.getTime() - hesuanList.get(0).getCreateTime().getTime();
//                        if (days <= (hesuanList.get(0).getExpDay().longValue() * (1000*3600*24L))) {
//                            result.put("green", "核酸检测有效期内");
//                            return result;
//                        }else if (days <= ((hesuanList.get(0).getExpDay().longValue() + orangeDay.longValue()) * (1000*3600*24L))) {
//                            result.put("orange", "核酸检测橙码有效期内");
//                            return result;
//                        }else {
//                            result.put("red", "核酸检测已过期");
//                            return result;
//                        }
//                    }else if(hesuanList.get(0).getJcResult() == 2){
//                        result.put("red", "阳性核酸检测");
//                        return result;
//                    }else {
//                        Hesuan hesuan = hesuanService.selectHsByStaff(staff.getId());
//                        if (null != hesuan) {
//                            if (hesuan.getJcResult() == 1) {
//                                Date curDate = new Date();
//                                long days = curDate.getTime() - hesuan.getCreateTime().getTime();
//                                if (days <= (hesuan.getExpDay().longValue() * (1000*3600*24L))) {
//                                    result.put("green", "核酸检测有效期内");
//                                    return result;
//                                }else if (days <= ((hesuan.getExpDay().longValue() + orangeDay.longValue()) * (1000*3600*24L))) {
//                                    result.put("orange", "核酸检测橙码有效期内");
//                                    return result;
//                                }else {
//                                    result.put("red", "核酸检测已过期");
//                                    return result;
//                                }
//                            }else {
//                                result.put("red", "核酸检测未出结果");
//                                return result;
//                            }
//                        }else {
//                            result.put("red", "没有做过核酸检测");
//                            return result;
//                        }
//                    }
//
//                }
            }
        }
        result.put("red", "没有做过核酸检测");
        return result;
    }

    /**
     * 根据企业ID获取企业下员工数量
     * @param qyId
     * @return
     */
    public Long getStaffCountByQyId (String qyId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("qyID", qyId);
        return staffDAO.selectCount(queryWrapper);
    }


    /**
     * 根据员工编号或者证件号码获取员工信息
     * @return
     */
    public Staff getStaffInfoByBhOrSfz (String param) {
        QueryWrapper<Staff> query = new QueryWrapper() ;
        final String params = param ;
        if(StringUtil.isNotNull(params)) {
            query.and(q -> {
                q.eq("bh",params).or().like("sfz","$#_"+ AES.encrypt(params)) ;
            }) ;
        }
        query.last("limit 1");
        return staffDAO.selectOne(query);
    }

    /**
     * 根据证件号码查询员工信息
     * @param sfz
     * @return
     */
    public Staff getStaffInfoBySfz (String sfz) {
        QueryWrapper query = new QueryWrapper();
        query.like("sfz", "$#_"+ AES.encrypt(sfz));
        query.eq("status", 1);
        query.last("limit 1");
        return staffDAO.selectOne(query);
    }


    /**
     * 生成员工编号
     * @return
     * @throws ParseException
     */
    public Map<String, String> genBh (Staff staff) throws ParseException {
        Map<String, String> resultMap = new HashMap<>();
        Pattern pattern1 = Pattern.compile("-?[0-9]+(\\\\.[0-9]+)?");
        Matcher mt1 = pattern1.matcher(staff.getName());
        if (mt1.matches()) {
            resultMap.put("error", "姓名不能是纯数字！");
            return resultMap;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String dateString = staff.getCstime();
        Date date = format.parse(dateString);
        String str[] = dateString.split("/");
        String monthStr = "";
        String dayStr = "";
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        // 获取出生年月，没有2位数则自动补0
        if (str[1].startsWith("0")) {
            monthStr = str[1];
        } else {
            monthStr = month >= 10 ? String.valueOf(month) : "0" + month;
        }
        if (str[2].startsWith("0")) {
            dayStr = str[2];
        }else {
            dayStr = day >= 10 ? String.valueOf(day) : "0" + day;
        }

        staff.setCstime(staff.getCstime());
        // 去数字
        String strNum = staff.getName().replaceAll("\\d+","");
        // 去空格
        String strName1 = StringUtils.deleteWhitespace(strNum);
        String regEx="[\n`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，·、？]";
        Pattern pt = Pattern.compile(regEx);
        Matcher mc = pt.matcher(strName1);
        // 去掉名字中的特殊字符
        String newName = mc.replaceAll("").trim();
        String tmpName = newName;

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");
        Matcher m = p.matcher(newName);
        String one = "";
        // 判断是否有中文
        if (m.find()) {
            Pattern pattern = Pattern.compile("[^\u4E00-\u9FA5]");
            Matcher matcher = pattern.matcher(newName);
            // 获取所有中文
            newName = matcher.replaceAll("");
            newName = StringUtils.deleteWhitespace(newName);
            // 中文个数
            if (newName.length() > 1) {
                // 截最后2位生成拼音首字母
                newName = newName.substring(newName.length() - 2);
                //newName = ChineseToEnglishUtil.getPinYinHeadChar(newName);
                newName = PinYinJPUtil.changeToGetShortPinYin(newName);
            }else if (newName.length() == 1) {
                // 取一个汉字拼音的前2位
                //newName = ChineseToEnglishUtil.getPingYin(newName);
                newName = PinYinJPUtil.changeToTonePinYin(newName);
                if (newName.length() == 1 && tmpName.length() > 1) {
                    Matcher m2 = p.matcher(tmpName);
                    if (m2.find()) {
                        Pattern pattern2 = Pattern.compile("[^\u4E00-\u9FA5]");
                        Matcher matcher2 = pattern2.matcher(tmpName);
                        // 获取所有中文
                        String tmpName1 = matcher2.replaceAll("");
                        String tmpName2 = StringUtils.deleteWhitespace(tmpName1);
                        // 获取中文之后的字符串
                        String str3 = tmpName.substring(0, tmpName.indexOf(tmpName2));
                        String str4 = tmpName.substring(str3.length()+1, tmpName.length());
                        Pattern pt2 = Pattern.compile(regEx);
                        Matcher mc2 = pt2.matcher(str3);
                        // 去掉中文前面特殊字符
                        String str6 = mc2.replaceAll("").trim();

                        Pattern pt3 = Pattern.compile(regEx);
                        Matcher mc3 = pt3.matcher(str4);
                        // 去掉中文前面特殊字符
                        String str7 = mc3.replaceAll("").trim();
                        //判断前面是否有两个字符
                        if (str6.length() >= 2) {
                            newName = str6.substring(0,2);
                        }else {
                            if(str7.length() > 1) {
                                newName = newName + str7.substring(0,1);  // lgh ------------------------
                            } else if (str7.length() == 1) {
                                newName = newName + str7;
                            }else {
                                resultMap.put("error", "姓名不符合规范！");
                                return resultMap;
                            }
                        }
                    }
                }else if (newName.length() == 1) {// 处理"啊"，"哦"，"额"单音
                    newName = newName + newName;
                }else {
                    if (newName!=null && newName.length()>2)
                    {
                        newName = newName.substring(0,2);
                    }
                }
            }
            // 中文名字转拼音首字母大写
            one = newName.toUpperCase();
        }else if(Pattern.compile("[a-zA-Z]").matcher(newName).find()){
            newName = newName.replaceAll("[^a-zA-Z]","");
            if (newName.length() > 1) {
                newName = newName.substring(0,2);
            }else if (newName.length() == 1){
                newName = newName + newName;
            }else {
            }
            one = newName.toUpperCase();
        }else if (Pattern.compile("[\u1000-\u109F]").matcher(newName).find()) {
            one = "MD";
        }else if (Pattern.compile("[\u0E80-\u0EFF]").matcher(newName).find()) {
            one = "LW";
        }else if (Pattern.compile("[\u0E00-\u0E7F]").matcher(newName).find()) {
            one = "TG";
        }

        Qiye qiye = qiyeService.selectID(staff.getQyID());
        Wuye wuye = wuyeService.selectID(qiye.getWyID());
        // 获取物业编码最后两位
        String tmpCode = String.valueOf(wuye.getWycode());
        if (tmpCode.length() < 2) {
            resultMap.put("error", "物业编码少于2位，无法生成员工编号！");
            return resultMap;
        }
        String two = tmpCode.substring(tmpCode.length() - 2);
        Dictionary dictionary = dictionaryService.getDicByName("Zy",staff.getZhiye());
        String tree = dictionary.getCode();
        String four = monthStr + dayStr;
        String monthStr2 = "";
        if (monthStr.equals("10")) {
            monthStr2 = "0" + monthStr;
        }else {
            monthStr2 = monthStr;
        }
        String dayStr2 = "";
        if (dayStr.equals("10")) {
            dayStr2 = "0" + dayStr;
        }else {
            dayStr2 = dayStr;
        }
        String four2 = monthStr2 + dayStr2;
        int five = 1;
        int six = 0;
        if (staff.getSex() == 1) {
            for (int j = 0; j < 10; j ++) {
                if (j % 2 == 0) {
                    continue;
                }
                six = j;
                break;
            }
        }else {
            for (int j = 0; j < 10; j ++) {
                if (j % 2 == 0) {
                    six = j;
                    break;
                }
                continue;
            }
        }
        String bh = one + two + tree + four + five + six;
        String bh2 = one + two + four2;
        String bh3 = generateBh(bh,staff.getSex());
        staff.setBh(bh3);
        staff.setBh2(bh2);
        return resultMap;
    }

    public String generateBh(String bh,Integer sex) {
        String tmpBh = bh.substring(0,bh.length()-1);
        String str = bh.substring(bh.length() - 1);
        char bh2 = bh.charAt(bh.length()-1);
        int num = (int) bh2;
        if (num > 47 && num < 58) {
            bh2 = (char) (bh2 - '0');
        }
        int i = 0;
        List<Staff> staffList = getStaffInfoByBh(bh);
        List<StaffHistory> staffHistoryList = staffHistoryService.getStaffHisByBh(bh);
        if (staffList.size() > 0) {
            if (sex == 1) {
                if (bh2 > 10) {
                    i = bh2 + 1;
                    tmpBh = tmpBh + (char)i;
                }else {
                    i = Integer.valueOf(bh2);
                    i = i + 2;
                    if (i > 10) {
                        i = 'X' + (i - 11) / 2;
                        tmpBh = tmpBh + (char)i;
                    }else {
                        tmpBh = tmpBh + i;
                    }
                }
            }else {
                if (bh2 > 10) {
                    i = bh2 + 1;
                    tmpBh = tmpBh + (char)i;
                }else {
                    i = Integer.valueOf(bh2);
                    i = i + 2;
                    if (i > 10) {
                        i = 'A' + (i - 10) / 2;
                        tmpBh = tmpBh + (char)i;
                    }else {
                        tmpBh = tmpBh + i;
                    }
                }
            }
            return generateBh(tmpBh,sex);
        }else {
            if (staffHistoryList.size() > 0) {
                if (sex == 1) {
                    if (bh2 > 10) {
                        i = bh2 + 1;
                        tmpBh = tmpBh + (char)i;
                    }else {
                        i = Integer.valueOf(bh2);
                        i = i + 2;
                        if (i > 10) {
                            i = 'X' + (i - 11) / 2;
                            tmpBh = tmpBh + (char)i;
                        }else {
                            tmpBh = tmpBh + i;
                        }
                    }
                }else {
                    if (bh2 > 10) {
                        i = bh2 + 1;
                        tmpBh = tmpBh + (char)i;
                    }else {
                        i = Integer.valueOf(bh2);
                        i = i + 2;
                        if (i > 10) {
                            i = 'A' + (i - 10) / 2;
                            tmpBh = tmpBh + (char)i;
                        }else {
                            tmpBh = tmpBh + i;
                        }
                    }
                }
                return generateBh(tmpBh,sex);
            }else {
                return bh;
            }
        }
    }

//    @Transactional(rollbackFor = Exception.class)
//    public void addStaff(StaffModal staff) throws Exception {
//        if(StringUtils.isNotBlank(staff.getId())){
//            Staff st = new Staff();
//            BeanUtils.copyProperties(staff,st);
//            if(StringUtils.isNotBlank(staff.getCreatetime())){
//                st.setCreatetime(DateUtil.parse(staff.getCreatetime()));
//            }
//            if(StringUtils.isNotBlank(staff.getRztime())){
//                st.setRztime(DateUtil.parse(staff.getRztime()));
//            }
//            if(StringUtils.isNotBlank(staff.getLztime())){
//                st.setLztime(DateUtil.parse(staff.getLztime()));
//            }
//            if(StringUtils.isNotBlank(staff.getZkTime())){
//                st.setZkTime(DateUtil.parse(staff.getZkTime()));
//            }
//            String fileName = System.currentTimeMillis() + ".png";
//            if(StringUtils.isNotBlank(staff.getPicture())){
//                MinioUtil minioUtil = new MinioUtil();
//                staff.setPicture(minioUtil.convertPrivateUrl(minioUtil.replacePrivateUrl(staff.getPicture(),BasicsUrl, PrivateBucketName), PrivateBucketName, AccessKey, SecretKey, Endpoint));
//                URL url = new URL(staff.getPicture());
////                HttpUtil.download(staff.getPicture(), new FileOutputStream(new File(upload + fileName)), true);
////                st.setPicture(uploadFile(staff.getPicture()));
//                IoUtil.copy(url.openStream(), new FileOutputStream(new File(upload + fileName)));
//                st.setPicture(fileName);
//            }
//            if (save(st)) {
//                if (StringUtil.isNotNull(st.getPicture())) {
////                    FileUtil.copy(tmp + st.getPicture(), upload, true);
//                    sshCopyFileService.copy(upload + st.getPicture());
//                    sshCopyFileService.copyToWjy(upload + st.getPicture());
//                    //tmp复制图片到upload
////                    String srcPathStr = tmp+staff.getPicture(); //源文件地址
////                    String desPathStr = upload; //目标文件地址
////                    copy(srcPathStr, desPathStr);
//                }
//                ChatStaff chatStaff = new ChatStaff();
//                chatStaff.setStaffId(staff.getId());
//                chatStaff.setNickname(MD5Util.generateShortUuid());
//                chatStaff.setImg("1623159572665.jpg");
//                chatStaff.setSex(staff.getSex());
//                chatStaff.setStatus(0);
//                chatStaff.setOnlineStatus(0);
//                chatStaff.setOtherTopic("otherChat/" + UUID.randomUUID().toString());
//                chatStaff.setNotifyTopic("notify/chat/" + UUID.randomUUID().toString());
//                chatStaff.setNotifyStatus(0);
//                chatStaffService.save(chatStaff);
//            } else {
//                //新增失败
//            }
//        }
//    }

//    private String uploadFile(String picture) {
//        File userIcon = new File(upload+"userIcon");
//        if (userIcon.exists()==false){
//            userIcon.mkdirs();
//        }
//        File tmpFile = new File(tmp);
//        if (tmpFile.exists()==false){
//            tmpFile.mkdirs();
//        }
//
//        try {
//            //网络图片资源的url（可以把这个放参数中动态获取）
//            String picUrl = picture;
//            //创建URL对象，参数传递一个String类型的URL解析地址
//            URL url = new URL(picUrl);
//            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
//            //从HTTP响应消息获取状态码
//            int code = huc.getResponseCode();
//            if (code == 200) {
//                //获取输入流
//                InputStream ips = huc.getInputStream();
//                byte[] buffer = new byte[1024];
//                int len = 0;
//                ByteArrayOutputStream bos = new ByteArrayOutputStream();
//                while ((len = ips.read(buffer)) != -1) {
//                    bos.write(buffer, 0, len);
//                }
//                bos.close();
//                return uploadFileByBytes(bos.toByteArray());
//            }
//            return "";
//        } catch (Exception e) {
//            return "";
//        }
//    }
    private String uploadFileByBytes(byte[] bytes) throws Exception {
        for (int i = 0; i < bytes.length; i++) {
            if (bytes[i] < 0) {
                bytes[i] += 256;
            }
        }

        String suffix=getSuffix(bytes);//获取图片的后缀名，也可以是其他任意文件名
        //根据系统时间拼一个当前新的文件名
        String newFileName = System.currentTimeMillis()+suffix;

        String realPath = tmp;
        //文件路径
        String url = realPath + newFileName;
        //判断文件路径是否存在，如果没有则新建文件夹
        File files = new File(realPath);
        if(!files.exists()){
            files.mkdirs();
        }
        //把文件写入到指定路径下
        try(OutputStream out = new BufferedOutputStream(new FileOutputStream(url, false))){
            out.write(bytes);
        }
        return newFileName;
    }

    public static String getSuffix(byte[] source){

        byte[] byteSuffix= Arrays.copyOf(source,3);

        String hexSuffix=bytesToHexString(byteSuffix);

        switch (hexSuffix){
            case "89504e":
                return ".png";
            case "ffd8ff":
                return ".jpg";
            default:
                return ".jpg";
        }

    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString().toLowerCase();
    }
//    @Transactional(rollbackFor = Exception.class)
//    public void updateStaff(StaffModal staff) throws Exception{
//        if(StringUtils.isNotBlank(staff.getId())){
//            Staff st = new Staff();
//            BeanUtils.copyProperties(staff,st);
//            if(StringUtils.isNotBlank(staff.getCreatetime())){
//                st.setCreatetime(DateUtil.parse(staff.getCreatetime()));
//            }
//            if(StringUtils.isNotBlank(staff.getRztime())){
//                st.setRztime(DateUtil.parse(staff.getRztime()));
//            }
//            if(StringUtils.isNotBlank(staff.getLztime())){
//                st.setLztime(DateUtil.parse(staff.getLztime()));
//            }
//            if(StringUtils.isNotBlank(staff.getZkTime())){
//                st.setZkTime(DateUtil.parse(staff.getZkTime()));
//            }
//            String fileName = System.currentTimeMillis() + ".png";
//            if(StringUtils.isNotBlank(staff.getPicture())){
//                MinioUtil minioUtil = new MinioUtil();
//                staff.setPicture(minioUtil.convertPrivateUrl(minioUtil.replacePrivateUrl(staff.getPicture(),BasicsUrl, PrivateBucketName), PrivateBucketName, AccessKey, SecretKey, Endpoint));
//                URL url = new URL(staff.getPicture());
////                HttpUtil.download(staff.getPicture(), new FileOutputStream(new File(upload + fileName)), true);
////                st.setPicture(uploadFile(staff.getPicture()));
//                IoUtil.copy(url.openStream(), new FileOutputStream(new File(upload + fileName)));
//                st.setPicture(fileName);
//            }
//            if (updateById(st)) {
//                Staff sta = selectID(staff.getId());
//                if (StringUtil.isNotNull(st.getPicture()) && st.getPicture().equals(sta.getPicture()) == false) {
////                    FileUtil.copy(tmp + st.getPicture(), upload, true);
//                    sshCopyFileService.copy(upload + st.getPicture());
//                    sshCopyFileService.copyToWjy(upload + st.getPicture());
//                    //tmp复制图片到upload
////                    String srcPathStr = tmp+staff.getPicture(); //源文件地址
////                    String desPathStr = upload; //目标文件地址
////                    copy(srcPathStr, desPathStr);
//                    List<Alert> alertList = alertService.getAlertByStaff(staff.getId());
//                    if (ValidateHelper.isNotEmptyCollection(alertList)) {
//                        for (Alert alert : alertList) {
//                            alertService.removeById(alert.getId());
//                        }
//                    }
//                }
//            } else {
//                //修改失败
//            }
//        }
//    }
//
//    @Transactional(rollbackFor = Exception.class)
//    public void batchOp(BatchOperationModel bo) throws Exception{
//        String[] staffIds = bo.getIds().split(",");
//        String msg = "";
//        for (String id : staffIds) {
//            Staff staff = selectID(id);
//            if (staff != null) {
//                staff.setZkFlag(bo.getStatus());
//                staff.setIsZsFlag(0);
//                staff.setIsAppStatus(0);
//                staff.setZkTime(DateUtil.parse(bo.getUpdatetime()));
//                String bh = StringUtils.deleteWhitespace(staff.getBh());
//                staff.setBh(bh);
//                if (!updateById(staff)) {
//                    throw new Exception("批量修改制卡状态失败");
//                }
//            }
//        }
//    }

    @Transactional(rollbackFor = Exception.class)
    public void batchStaffZhiYe(BatchUpdateStaffZhiYeModel model) {
        UpdateWrapper<Staff> uw = new UpdateWrapper<>();
        uw.eq("qyID", model.getCompanyId());
        Staff staff = new Staff();
        staff.setZhiye(model.getZhiye());
        staffDAO.update(staff, uw);
    }

//    @Transactional(rollbackFor = Exception.class)
//    public void UpdateStaffPassword(UpdateStaffPasswordModel updateStaffPasswordModel) throws Exception{
//        if(StringUtils.isNotBlank(updateStaffPasswordModel.getId())){
//            LambdaUpdateWrapper<Staff> wrapper = new LambdaUpdateWrapper<>();
//            wrapper.eq(Staff::getId,updateStaffPasswordModel.getId());
//            wrapper.set(Staff::getPassword, PasswordUtil.jiami(updateStaffPasswordModel.getPassword()));
//            int n = staffDAO.update(null,wrapper);
//            if(n < 1){
//                throw new Exception("修改密码失败！");
//            }
//        }
//    }
}
